<?php
namespace app\spadmin\controller\system;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
class Web extends Backend{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Config');
    }

    public function site(){
        $row = $this->model->all();
        $this->assign('list',$row);
        return $this->view->fetch();
    }

    public function edit($ids=null){
        if($this->request->isPost()){
            $row = $this->request->post("", [], 'trim');
            if ($row) {
                $configList = [];
                foreach ($this->model->all() as $v) {
                    if (isset($row[$v['name']])) {
                        if($v['type'] == 'boolean'){
                            $v['value'] = intval($row[$v['name']]);
                        }else{
                            $v['value'] = $row[$v['name']];
                        }
                        $configList[] = $v->toArray();
                    }
                }

                try {
                    $this->model->allowField(true)->saveAll($configList);
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                try {
                    $config = [];
                    foreach ($configList as $k => $v) {
                        $config[$v['name']] = $v['value'];
                    }
                    file_put_contents(
                        CONF_PATH . 'extra' . DS . 'site.php',
                        '<?php' . "\n\nreturn " . var_export($config,true) . ";\n"
                    );
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                $this->success('操作成功');
            }
            $this->error("配置参数不能为空");
        }
    }
}